package com.ylkj.wx.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;
import com.ylkj.wx.constant.WeiXBaseConstant;

/**
 * 
 * <p>GET和POST方式访问微信接口API获取用户、Access_token等信息的工具</p>
 * <p>@Since 2015年2月5日 上午9:29:42</p>
 * @author <a href=luoqi@neusoft.com>罗琦</a>
 */
public final class HttpUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    private static final String UTF_8 = "UTF-8";

    private static final String STATUS_CODE = "HTTP STATUS CODE:";

    private HttpUtils() {

    }

    /**
     * 
     * Get方式访问微信API
     * 
     * @param url 微信接口API路径
     * @return String 获取到的信息
     * @throws IOException
     * @throws HttpException
     */
    public static String getContentByGet(String url) throws IOException {
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        String content = "";
        try {
            httpClient.executeMethod(getMethod);
            //content = getMethod.getResponseBodyAsString();
            content = new String(getMethod.getResponseBody(), "utf-8");
            LOGGER.info("status is " + getMethod.getStatusLine());
        } finally {
            getMethod.releaseConnection();
        }
        return content;
    }

    /**
     * http post 请求
     * 
     * @param url
     * @param parameters
     * @return
     */
    public static String post(String url, Map<String, String> parameters) {
        int statusCode = 0;
        HttpClient httpclient = new HttpClient();
        PostMethod method = new PostMethod(url);
        String result = "";

        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        // 设置内容字符集
        method.getParams().setContentCharset(UTF_8);
        // 设置参数，可在request中获得
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            method.addParameter(entry.getKey(), entry.getValue());
        }

        InputStream inputStream = null;
        BufferedReader br = null;
        try {
            statusCode = httpclient.executeMethod(method);
            LOGGER.debug(STATUS_CODE + statusCode);
            inputStream = method.getResponseBodyAsStream();
            br = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer stringBuffer = new StringBuffer();
            String str;
            while ((str = br.readLine()) != null) {
                stringBuffer.append(str);
            }
            result = stringBuffer.toString();
        } catch (HttpException e) {
            LOGGER.error(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage());
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        } finally {
            try {
                if(null != inputStream) {
                    inputStream.close();
                }
                if(null != br) {
                    br.close();
                }
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }
            method.releaseConnection();
        }
        return result;
    }

    public static String post(String url, String s) throws IOException, ExecutionException, InterruptedException {
        AsyncHttpClient http = new AsyncHttpClient();
        AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
        builder.setBodyEncoding(WeiXBaseConstant.DEFAULT_CHARSET);
        builder.setBody(s);
        Future<Response> f = builder.execute();
        String body = f.get().getResponseBody(WeiXBaseConstant.DEFAULT_CHARSET);
        http.close();
        return body;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String getRequestUrl(HttpServletRequest request){
        String requestUrl  = request.getScheme()+"://"; //请求协议 http 或 https
        requestUrl+=request.getHeader("host");  // 请求服务器
        requestUrl+=request.getRequestURI();     // 工程名
        //判断请求参数是否为空
        if(request.getQueryString()!=null){
            requestUrl+="?"+request.getQueryString();   // 参数
        }
        return requestUrl;
    }
}
